// pages/buyCarte/buyCarte.js
import { carte_order, get_carte, unified_order, carte_order_v4, unified_order_v4} from '../../utils/api.js'
import { MD5 } from '../../utils/MD5.js'

let app = getApp();
var haveTap = 0; // 屏蔽重复点击
Page({
  /**
   * 页面的初始数据
   */
  data: {
    payStatus: 0, // 0 发起支付，1 需要填写手机号
    TaskShow: 0, //默认0  1 填写手机号
    TaskShow1: 0,
    phone: '',
    code: '',
    codePlace: '获取验证码',
    setInter: '',
    payPrice: '',
    content: '',
    ischecked: true,
    region: ['北京市', '北京市', '东城区'],
   
    chage_status: 0,
    province: 0,
    city: 0,
    area: 0,
    invite_code:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let CarteInfo = JSON.parse(decodeURIComponent(options.params));
    CarteInfo.img.src = CarteInfo.img.src + '?x-oss-process=style/index_mp';
    
    CarteInfo.comLogo.src = CarteInfo.comLogo.src + '?x-oss-process=style/goods_skeletonize';
    this.setData({
      userInfo: app.globalData.userInfo,
      CarteInfo: CarteInfo,
      shareOptions: JSON.parse(JSON.stringify(app.globalData.shareOptions))
    })
    haveTap = 0
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkPhone();
    var that = this;
    var url = "/cardshop_api/card_price";
    var params = {}
    app.HttpPostSend(url, {},
      function (result_data) {
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {
          that.setData({
            payPrice: result_data.data.card
          })
        }
      })

    var url2 = "/cardshop_api/card_word";
    var params2 = {
      type: 1
    }
    app.HttpPostSend(url2, params2,
      function (result_data) {
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {
          if (!!result_data.data) {
            that.setData({
              content: result_data.data.content
            })
          }
        }
      })
  },

  // 判断是否有手机号
  checkPhone: function () {
    if (!app.phoneReg(app.globalData.userInfo.phone) && !app.globalData.userInfo.register_province) {

      this.setData({
        payStatus: 1
      })
    } else if (app.phoneReg(app.globalData.userInfo.phone) && !app.globalData.userInfo.register_province) {
      this.setData({
        payStatus: 2
      })
    } else {

      this.setData({
        payStatus: 0
      })
    }
  },

  bindRegionChange: function (e) {

    this.setData({
      region: e.detail.value,
      chage_status: 1,
      province: e.detail.code[0],
      city: e.detail.code[1],
      area: e.detail.code[2],
    })
  },

  // 打开添加手机号弹窗
  showPhoneTask: function () {
    if (this.data.ischecked == false) {
      app.showTipMsg('请同意协议');
      return false;
    }
    this.setData({
      TaskShow: 1,
    })
  },

  showPhoneTask1: function () {
    if (this.data.ischecked == false) {
      app.showTipMsg('请同意协议');
      return false;
    }
    this.setData({
      TaskShow1: 1,
    })
  },

  //输入手机号
  inputgetPhone: function (e) {
    this.setData({
      phone: e.detail.value
    });
  },

  //输入验证码
  inputgetCode: function (e) {
    this.setData({
      code: e.detail.value
    });
  },

  //获取验证码
  getCode: function (e) {
    const that = this
    if (haveTap == 1) {
      console.log('屏蔽重复点击')
    } else {
      haveTap = 1;
      try {
        let url = '/ali_msg_api/sendMsg';
        let params = {
          phone: that.data.phone
        };
        app.HttpPostSend(url, params, function (res) {
          if (res.code != "1") {
            // app.showTipMsg(res.data);
            wx.showModal({
              title: '提示',
              content: res.data,
              showCancel: false,
              success: function () { }
            })
            haveTap = 0;
            that.setData({
              codePlace: "重新发送"
            })
          } else {
            var curCount = 60;
            that.setData({
              codePlace: curCount + "s"
            })
            that.data.setInter = setInterval(function () {
              if (curCount == 1) {
                clearInterval(that.data.setInter);
                that.setData({
                  codePlace: "重新发送"
                })
              } else {
                curCount = Number(curCount) - 1;
                that.setData({
                  codePlace: curCount + "s"
                })
              }
            }, 1000);
          }
        });
        haveTap = 0;
      } catch (error) {
        console.log(error)
        haveTap = 0;
      }
    }
  },

  //关闭手机号弹窗
  closePhoneShow: function (e) {
    this.setData({
      TaskShow: 0,
    })
  },

  closePhoneShow1: function (e) {
    this.setData({
      TaskShow1: 0,
    })
  },

  // 添加手机号
  addPhone: function () {
    const that = this
    if (!app.phoneReg(that.data.phone)) {
      wx.showToast({
        title: '输入正确的手机号',
        icon: 'none',
        duration: 1000
      })
      haveTap = 0;
      return false;
    }
    if (!that.data.area) {
      wx.showToast({
        title: '请选择注册地',
        icon: 'none',
        duration: 1000
      })
      haveTap = 0;
      return false;
    }



    if (haveTap == 1) {
      console.log('屏蔽重复点击')
    } else {
      haveTap = 1;
      try {
        let url = "/user_api/phoneAuth1_v4";
        var param = {
          uid: that.data.userInfo.id,
          phone: that.data.phone,
          code: that.data.code,
          province: that.data.province,
          city: that.data.city,
          area: that.data.area,
          invite_code: that.data.invite_code,
          parent_id: that.data.CarteInfo.id,
          timestamp: new Date().getTime(),
        }
        param.sign = app.getSign(param)
        app.HttpPostSend(url, param ,
          function (result_data) {
            if (result_data.msg != "success") {
              app.showTipMsg(result_data.msg);
            } else {
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                TaskShow: 0,
                payStatus: 0,
                userInfo: result_data.data
              })
              clearInterval(that.data.setInter);
              that.startPay();
            }
          })
        haveTap = 0;
      } catch (error) {
        console.log(error)
        haveTap = 0;
      }
    }
  },
  addarea: function () {
    const that = this

    if (!that.data.area) {
      wx.showToast({
        title: '请选择注册地',
        icon: 'none',
        duration: 1000
      })
      haveTap = 0;
      return false;
    }

    if (haveTap == 1) {
      console.log('屏蔽重复点击')
    } else {
      haveTap = 1;
      try {
        let url = "/user_api/areaAuth_v4";
        var param = {
          uid: that.data.userInfo.id,
          province: that.data.province,
          city: that.data.city,
          area: that.data.area,
          invite_code: that.data.invite_code,
          parent_id: that.data.CarteInfo.id,
          timestamp: new Date().getTime(),
        }
        param.sign = app.getSign(param)
        app.HttpPostSend(url, param,
          function (result_data) {
            if (result_data.msg != "success") {
              app.showTipMsg(result_data.msg);
            } else {
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                TaskShow1: 0,
                payStatus: 0,
                userInfo: result_data.data
              })
              clearInterval(that.data.setInter);
              that.startPay();
            }
          })
        haveTap = 0;
      } catch (error) {
        console.log(error)
        haveTap = 0;
      }
    }
  },

  // 开始支付
  startPay: function () {
    if (this.data.ischecked == false) {
      wx.showToast({
        title: '请同意协议',
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    const that = this
    if (haveTap == 1) {
      console.log('屏蔽重复点击')
      return;
    }
    haveTap = 1;
    // 雷达添加查看记录 -名片付款数
    app.radarAdd(that.data.CarteInfo.id, 15,'','',app.globalData.userInfo.logo)

    // 发送模板消息-访客到访通知
    // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '购买名片付款中', '', '', '')

    const shareOptions = this.data.shareOptions
    console.log('测试有没有userid111：', app.globalData.userInfo.id);
    if (!app.globalData.userInfo.id) {
      wx.showToast({
        title: '清除缓存后重试',
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    try {
      wx.showLoading({
        title: '支付中',
      })
      let params = {
        uid: app.globalData.userInfo.id,
        parent_id: that.data.CarteInfo.id,
        invite_id: !!shareOptions.share_id ? shareOptions.share_id : shareOptions.invite_id,
        price: that.data.payPrice,
        timestamp: new Date().getTime(),
      }
      params.sign = app.getSign(params)
      app.HttpPostSend(carte_order_v4, params, function (res) {
        wx.hideLoading();
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          // console.log(res)
          let params2 = {
            order_source: 1,
            total_fee: that.data.payPrice * 100,
            openid: app.globalData.openid,
            order_id: res.data,
            body: '尽猎AI门店帮扶系统',
            type: 2 + '',
            timestamp: new Date().getTime(),
          }
          params2.sign = app.getSign(params2)
          app.HttpPostSend(unified_order_v4, params2, function (unified_order_res) {
            if (unified_order_res.msg != "success") {
              app.showTipMsg(unified_order_res.msg);
            } else {
              // console.log(unified_order_res)
              let order_arr = unified_order_res.data.order_arr
              let signA = "appId=" + order_arr.appid + "&nonceStr=" + order_arr.noncestr + "&package=prepay_id=" + order_arr.prepayid + "&signType=MD5&timeStamp=" + order_arr.timestamp;
              let signB = signA + "&key=" + unified_order_res.data.key
              let new_pay_sign = MD5(signB)
              // console.log(new_pay_sign)
              wx.requestPayment({
                timeStamp: order_arr.timestamp,
                nonceStr: order_arr.noncestr,
                package: 'prepay_id=' + order_arr.prepayid,
                signType: 'MD5',
                profit_sharing: 'Y',
                paySign: new_pay_sign,
                success(pay_res) {
                  // console.log(pay_res)
                  // that.updateUserCard();
                  that.updateUserStatus(app.globalData.userInfo.id, that.data.CarteInfo.id, app.globalData.invite_id)
                  // 雷达添加查看记录 -名片付款成功数
                  // app.radarAdd(app.globalData.SwitchTabParams.v_id, 16)

                  // 发送模板消息-访客到访通知
                  // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter?coming_status=1', '付款成功', '', '', '')

                  haveTap = 1;
                },
                fail(err_res) {
                  // console.log(err_res)
                  haveTap = 0;

                },
                complete() { }
              })
            }
          })
        }
      })
    } catch (error) {
      console.log(error)
      haveTap = 0;
    }
  },

  // 回调改变用户身份
  updateUserCard: function (uid) {
    const that = this
    var url = "/user_api/updateUserStatus";
    var params = {
      uid: app.globalData.userInfo.id,
      parent_id: that.data.CarteInfo.id,
      invite_id: !!app.globalData.shareOptions.share_id ? app.globalData.shareOptions.share_id : app.globalData.shareOptions.invite_id
    }
    app.HttpPostSend(url, params,
      function (result_data) {
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {

          that.updateUserStatus(app.globalData.userInfo.id, that.data.CarteInfo.id, app.globalData.invite_id)

        }
      })
  },

  // 改变用户信息
  updateUserStatus: function (uid) {
    const that = this
    app.HttpGetSend(
      get_carte, {
        uid: uid,
        v_id: uid
      },
      function (result_data) {
        // console.log(res)
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {
          app.globalData.userInfo = {
            ...result_data.data
          }
          wx.setStorage({
            key: 'userInfo',
            data: JSON.stringify({
              ...result_data.data
            })
          })
          wx.redirectTo({
            url: '/pages/paySuccess/paySuccess?price=' + that.data.payPrice + '&type=' + 1 + '&carte_id=' + that.data.CarteInfo.id,
          })
        }
      })
  },

  //勾选同意协议
  changeCheck: function () {
    this.setData({
      ischecked: !this.data.ischecked
    })
  },

  //进入使用协议
  showAgreement: function () {
    wx.navigateTo({
      url: '/pages/agreement/agreement',
    })
  },

  //进入隐私协议
  showAgreementUs: function () {
    wx.navigateTo({
      url: '/pages/agreementUs/agreementUs',
    })
  },
  code_input:function(e){
    var that = this;
    var code = e.detail.value;
    that.setData({
      invite_code: code
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    clearInterval(that.data.setInter);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    clearInterval(that.data.setInter);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})